package cn.edu.scau.cmi.xiaozecheng.client;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

import java.util.List;
import java.util.Optional;

import cn.edu.scau.cmi.xiaozecheng.composite.consistent.Organization;
import cn.edu.scau.cmi.xiaozecheng.composite.consistent.Person;
import cn.edu.scau.cmi.xiaozecheng.composite.consistent.Team;

/**
 * @author xiao
 */
public class ConsistentCompositeClient extends Application {
    private TextField input = new TextField();
    private Button addTeam = new Button("addTeam");
    private Button addPerson = new Button("addPerson");
    private Button delete = new Button("delete");
    private final Team team = new Team("root");
    private TreeItem<Organization> rootItem = new TreeItem<>();
    private TreeView<Organization> tree = new TreeView<>(rootItem);

    public static void main(String[] args) {
        launch(args);
    }

    private void refreshTree() {
        rootItem = new TreeItem<>(team);
        tree.setRoot(rootItem);
        addItem(team, rootItem);
        tree.getSelectionModel().selectLast();
    }

    @SuppressWarnings("all")
    public void addItem(Organization organization, TreeItem parent) {
        List<Organization> list = organization.getChilds();
        if (list == null) {
            return;
        } else {
            for (int i = 0; i < list.size(); i++) {
                TreeItem<Organization> treeItem = new TreeItem(list.get(i));
                parent.getChildren().add(treeItem);
                addItem(list.get(i), treeItem);
            }
        }
        parent.setExpanded(true);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("consistent");


        BorderPane root = new BorderPane();
        tree.getSelectionModel().select(0);
        HBox box = new HBox();

        input.setMinWidth(30);

        box.getChildren().addAll(input, addTeam, addPerson, delete);
        box.setAlignment(Pos.BASELINE_CENTER);

        root.setTop(box);
        root.setCenter(tree);
        primaryStage.setScene(new Scene(root, 800, 600));
        primaryStage.show();
        refreshTree();
        addPerson.setOnAction(event -> {
            if (checkNullInput()) {
                return;
            }
            String inputString = input.getText().trim();
            Organization organization = tree.getSelectionModel().getSelectedItem().getValue();
            Person person = new Person(inputString);
            if (organization instanceof Team) {
                organization.addChild(person);
            } else {
                Organization parent = (Organization) getSelectTreeItem().getParent().getValue();
                Organization tmp = (Organization) getSelectTreeItem().getValue();
                parent.getChilds().remove(tmp);
                String newTeam = formTeam();
                Team team = new Team(newTeam);
                team.addChild(person);
                team.addChild(tmp);
                parent.addChild(team);
            }
            input.clear();
            refreshTree();
        });

        delete.setOnAction(event -> {
            TreeItem treeItem = getSelectTreeItem().getParent();
            Organization team = (Organization) treeItem.getValue();
            team.getChilds().remove(getSelectOrganization());
            refreshTree();
        });

        addTeam.setOnAction(event -> {
            if (checkNullInput()) {
                return;
            }
            String inputString = input.getText().trim();
            Organization organization = tree.getSelectionModel().getSelectedItem().getValue();
            Team team = new Team(inputString);
            if (organization instanceof Team) {
                organization.addChild(team);
            } else {
                Organization parent = (Organization) getSelectTreeItem().getParent().getValue();
                parent.addChild(team);
                team.addChild(organization);
                ((Organization) getSelectTreeItem().getParent().getValue()).getChilds().remove(getSelectOrganization());
            }
            input.clear();
            refreshTree();
        });
    }

    /**
     * @return 空输入返回true
     */
    private boolean checkNullInput() {
        if (input.getText().trim().length() == 0) {
            Alert alert = new Alert(Alert.AlertType.ERROR, "请输入");
            alert.showAndWait();
            return true;
        }
        return false;
    }

    private Organization getSelectOrganization() {
        return tree.getSelectionModel().getSelectedItem().getValue();
    }

    private TreeItem getSelectTreeItem() {
        return tree.getSelectionModel().getSelectedItem();
    }

    private String formTeam() {
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle("Text Input Dialog");
        dialog.setHeaderText("输入生成的团体名");
        dialog.setContentText("Please enter the new team name:");
        Optional<String> result = dialog.showAndWait();
        return result.orElse("");
    }
}